package pers.lan.th.java.semaphore;

import java.util.concurrent.Semaphore;

/**
 * @author <p><a href="mailto:1728209643@qq.com">XiaoSan</a>
 * @date 2019/11/28 8:17 PM
 */
public class Semaphore_ {

    public static void main(String[] args) {
        int n = 8;
        Semaphore semaphore = new Semaphore(5);
        for (int i = 0; i < n; i++) {
            new Worker(i, semaphore).start();
        }
    }

    static class Worker extends Thread {
        private int num;

        private Semaphore semaphore;

        public Worker(int num, Semaphore semaphore) {
            this.num = num;
            this.semaphore = semaphore;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire(num);
                System.out.println(Thread.currentThread().getId() + "\t" + num);
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getId() + "\t释放");
                semaphore.release(num);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
